package org.way.base.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class MsgAspect {

    @Pointcut("@annotation(org.way.base.aop.Msg)")
    void pointCut() {

    }

    @After("pointCut()")
    public void after(JoinPoint point) {
        MethodSignature signature = (MethodSignature)point.getSignature();
        Method method = signature.getMethod();
        Msg annotation = method.getAnnotation(Msg.class);

        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        String desc = annotation.desc();

        Object[] args = point.getArgs();
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        if(args != null && parameterNames != null) {
            for (int i = 0; i < args.length; i++) {
                log.info(parameterNames[i] + ": " + args[i]);
            }
        }

        log.info("className :{},methodName: {},desc :{}",className,methodName,desc);
    }

}
